﻿using AutoMapper;
using B.S.Medical.Api.Write.Application.Command.Doctor;
using B.S.Medical.Domain.Doctor;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using B.S.Medical.Domain.Medical;

namespace B.S.Medical.Api.Write.Application.Handler.Doctor
{
    /// <summary>
    /// 批量删除医生处理器
    /// </summary>
    public class DeleteDoctorHandler : IRequestHandler<BatchDeleteDoctorCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<DoctorModel> _doctorRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<DeleteDoctorHandler> _logger;
        private readonly IBaseRepository<DoctorScheduleModel> _doctorScheduleRepository;

        public DeleteDoctorHandler(IBaseRepository<DoctorModel> doctorRepository,
                                  IMapper mapper,
                                  ILogger<DeleteDoctorHandler> logger,
                                  IBaseRepository<DoctorScheduleModel> doctorScheduleRepository)
        {
            _doctorRepository = doctorRepository;
            _mapper = mapper;
            _logger = logger;
            _doctorScheduleRepository = doctorScheduleRepository;
        }

        public async Task<ApiResult<int>> Handle(BatchDeleteDoctorCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            try
            {
                var doctors = _doctorRepository.GetAll().Where(d => request.DoctorIds.Contains(d.Id) && !d.IsDeleted).ToList();
                if (doctors == null || doctors.Count == 0)
                {
                    res.Msg = "未找到要删除的医生!";
                    res.Code = ApiEnum.Fail;
                    _logger.LogError($"未找到要删除的医生，IDs:{string.Join(",", request.DoctorIds)}");
                    return res;
                }
                // 判断是否有排班
                foreach (var doctor in doctors)
                {
                    bool hasSchedule = _doctorScheduleRepository.GetAll().Any(s => s.DoctorId == doctor.Id && !s.IsDeleted);
                    if (hasSchedule)
                    {
                        res.Msg = $"医生【{doctor.DoctorName}】存在排班，无法删除！";
                        res.Code = ApiEnum.Fail;
                        _logger.LogWarning($"医生存在排班，无法删除，ID:{doctor.Id}");
                        return res;
                    }
                }
                foreach (var doctor in doctors)
                {
                    doctor.IsDeleted = true;
                }
                var result = await _doctorRepository.UpdateRangAsync(doctors);
                if (result > 0)
                {
                    res.Msg = "批量删除医生成功!";
                    res.Code = ApiEnum.Success;
                    res.Data = result;
                    _logger.LogInformation($"批量删除医生成功，IDs:{string.Join(",", request.DoctorIds)}");
                }
                else
                {
                    res.Msg = "批量删除医生失败!";
                    res.Code = ApiEnum.Fail;
                    res.Data = result;
                    _logger.LogError($"批量删除医生失败，IDs:{string.Join(",", request.DoctorIds)}");
                }
                return res;
            }
            catch (System.Exception ex)
            {
                res.Msg = "批量删除医生异常: " + ex.Message;
                res.Code = ApiEnum.Fail;
                _logger.LogError(ex, $"批量删除医生异常: {ex.Message}");
                return res;
            }
        }
    }
}
